package top.mh.mybatis.config;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import top.mh.mybatis.pojo.Configuration;
import top.mh.mybatis.pojo.MappedStatement;

import java.io.InputStream;
import java.util.List;

/**
 * @author mh
 * @version 1.0
 * @description 解析mapper.xml文件信息
 * @since 2024/2/2 16:03
 */
public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 解析mapper.xml文件的sql信息：
     * (1) 获取命名空间
     * (2) 获取select、insert、update、delete等标签，并解析其中的
     *      id、parameterType、resultType 和其中的sql语句，封装成mapperStatement对象
     * (3) 将mapperStatement对象存储到configuration对象中
     * @param inputStream mapper.xml文件输入流
     */
    public void parse(InputStream inputStream) throws Exception {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        // 1.获取命名空间
        String namespace = rootElement.attributeValue("namespace");

        /**
         * 2.解析CURD标签，一条sql语句就是一个mapperStatement对象
         *  <select id="selectOne" resultType="top.mh.pojo.User" parameterType="top.mh.pojo.User">
         *        select * from user where id = #{id} and username = #{username}
         *  </select>
         */
        List<Node> nodeList = rootElement.selectNodes("//select");
        for (Node node : nodeList) {
            Element element = (Element) node;
            String id = element.attributeValue("id");
            String parameterType = element.attributeValue("parameterType");
            String resultType = element.attributeValue("resultType");
            String sql = element.getTextTrim();

            // statementId: namespace.id
            String statementId = namespace + "." + id;

            // 封装mapperStatement对象
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setStatementId(statementId);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sql);
            mappedStatement.setSqlCommandType("select"); // CRUD类型,用于mapper代理

            // 将封装好的mappedStatement封装到configuration中的map集合中
            configuration.getMappedStatementMap().put(statementId, mappedStatement);
        }
    }
}
